package org.example.netty.dev2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

public class EchoServer {

    private int port;
    public EchoServer(int port){
        this.port = port;
    }

    public void start(){
        EventLoopGroup bossGrop = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGrop,workGroup);
        bootstrap.localAddress(this.port);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                System.out.println("报告");
                System.out.println("信息：有一客户端链接到本服务端");
                System.out.println("IP:" + ch.localAddress().getHostName());
                System.out.println("Port:" + ch.localAddress().getPort());
                System.out.println("报告完毕");
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new StringEncoder(Charset.forName("GBK")));
                pipeline.addLast(new EchoServerHandler());
                pipeline.addLast(new ByteArrayEncoder());
            }
        });
            ChannelFuture cf = bootstrap.bind().sync(); // 服务器异步创建绑定
            System.out.println(EchoServer.class + " 启动正在监听： " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGrop.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        new EchoServer(9000).start();
    }
}
